﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace AGif
{
    public class ScreenDescriptor : Component
    {
        public ushort   width;
        public ushort   height;

        #region Packed Byte

        public char    GlobalColorTable;        //Default True
                                                //Color resolution will be 111 by default
        public char     SortFlag;               //Default False
                                                //Color Table size will be 111 by default (for now)
        #endregion

        public char     BackGroundColorIndex;   //Defualt True
        public char     PixelAspectRatio;       //Default False

        public ScreenDescriptor()
        {
            width                   = 0;
            height                  = 0;

            GlobalColorTable        = (char)1;
            SortFlag                = (char)0;
            BackGroundColorIndex    = GlobalColorTable;
            PixelAspectRatio        = (char)0;
        }

        public byte[] Save()
        {
            List<byte> bContainer = new List<byte>();

            bContainer.AddRange(BitConverter.GetBytes(width));
            bContainer.AddRange(BitConverter.GetBytes(height));

            //Create and Save Packed Byte
            //G111-S111

            char packedByte = new char();

            packedByte |= (char)(GlobalColorTable << 7);    //Global Color Table
            packedByte |= (char)(112);                      //Color Resolution
            packedByte |= (char)(SortFlag << 3);            //Sort Flag
            packedByte |= (char)(7);                        //Color Table Size


            bContainer.AddRange(BitConverter.GetBytes(BackGroundColorIndex));
            bContainer.AddRange(BitConverter.GetBytes(PixelAspectRatio));

            return bContainer.ToArray();
        }

        public void Load(Stream stream)
        {
            byte[] bWidth       = new byte[2];
            byte[] bHeight      = new byte[2];
            byte[] bPack        = new byte[1];
            byte[] bColorIndex  = new byte[1];
            byte[] bAspect      = new byte[1];


            stream.Read(bWidth, 0, 2);
            stream.Read(bHeight, 0, 2);
            stream.Read(bPack, 0, 1);
            stream.Read(bColorIndex, 0, 1);
            stream.Read(bAspect, 0, 1);

            width                   = BitConverter.ToUInt16(bWidth, 0);
            height                  = BitConverter.ToUInt16(bHeight, 0);
            char pack               = BitConverter.ToChar(bPack, 0);
            BackGroundColorIndex    = BitConverter.ToChar(bColorIndex, 0);
            PixelAspectRatio        = BitConverter.ToChar(bAspect, 0);


            //G111-S111

            GlobalColorTable = (char)((pack & 128) >> 7);

        }
    }
}
